#include <grpcpp/grpcpp.h>

#include <iostream>
#include <memory>
#include <string>

#include "hello.grpc.pb.h"

using namespace std;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using hello::Greeter;
using hello::HelloRequest;
using hello::HelloResponse;

// 实现服务
class GreeterService final : public Greeter::Service {
public:
    Status SayHello(ServerContext* context, const HelloRequest* request, HelloResponse* response) override {
        cout << "HelloRequest: " << request->name() << endl;
        google::protobuf::RepeatedPtrField< ::hello::FieldData> field = request->fields_data();
        for (auto& item : field) {
            cout << "HelloRequest type: " << item.type() << " name: " << item.field_name() << endl;
        }

        string prefix("Hello ");
        response->set_message(prefix + request->name());
        return Status::OK;
    }
};

void runServer() {
    string address("0.0.0.0:50051");
    GreeterService service;
    ServerBuilder builder;

    builder.AddListeningPort(address, grpc::InsecureServerCredentials());
    builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS, 5000);
    builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 10000);
    builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1);
    builder.RegisterService(&service);

    unique_ptr<Server> server(builder.BuildAndStart());
    cout << "Server listening on " << address << endl;

    // 进入服务循环
    server->Wait();
}

int main() {
    runServer();
    cout << "hello world" << endl;

    return 0;
}
